<?php
namespace app\middleware;

use app\exception\ApiException;
use app\model\Game;
use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;

class GameSignMiddleware extends SignMiddleware
{
    protected $sign_key = '';
    public function process(Request $request, callable $handler) : Response
    {
        $Game = new Game();
        $game_id = $request->input('game_id',0);
        $this->sign_key = $Game->where('id',$game_id)->value('game_secret');
        if(empty($this->sign_key)) throw new ApiException('game or package no game_secret',CODE_SIGN_ERROR);
        /*if(empty($package_id)){

            $game_id = $request->input('game_id',0);
            $config = $Game->getGameConfigByGameId($game_id);
            $this->sign_key = $config['game_secret'] ?? '';
            //throw new ApiException('package_id empty',CODE_SIGN_ERROR);
        }else{
            $package_ids = explode(',',$package_id);
            $configList = $Game->getGameConfig($package_ids,true);
            if(empty($configList)) throw new ApiException('package_id is non-existent',CODE_SIGN_ERROR);
            $game_ids = array_unique(array_column($configList,'game_id'));
            if(count($game_ids)!=1){
                throw new ApiException('package_is is not  belong same game',CODE_SIGN_ERROR);
            }
            $game = current($configList);
            $this->sign_key = $game['game_secret'] ?? '';

        }*/

        $this->check($request);
        $response = $handler($request); // 继续向洋葱芯穿越，直至执行控制器得到响应

        return $response;
    }

}